package com.web709.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.web709.common.R;
import com.web709.entity.User;
import com.web709.entity.Volunteer;
import com.web709.service.VolunteerService;
import com.web709.util.JwtUtils;
import com.web709.util.SMSUtils;
import com.web709.util.ValidateCodeUtils;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/volunteer")
@Api(tags = "志愿者管理接口")
@Slf4j
public class VolunteerController {
    @Autowired
    private VolunteerService volunteerService;

    @Autowired
    private SMSUtils smsUtils;

    @GetMapping("/list")
    @ApiOperation(value = "获取志愿者列表", notes = "分页查询所有志愿者信息，支持按姓名、学院搜索和时间范围")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "page", value = "页码（从1开始）", defaultValue = "1", dataType = "Integer", paramType = "query"),
        @ApiImplicitParam(name = "size", value = "每页数量", defaultValue = "10", dataType = "Integer", paramType = "query"),
        @ApiImplicitParam(name = "name", value = "志愿者姓名", required = false, dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "college", value = "学院", required = false, dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "sex", value = "性别", required = false, dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "clazz", value = "班级", required = false, dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "stuId", value = "学号", required = false, dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "startTime", value = "开始时间 (格式: YYYY-MM-DD HH:mm:ss)", required = false, dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "endTime", value = "结束时间 (格式: YYYY-MM-DD HH:mm:ss)", required = false, dataType = "String", paramType = "query")
    })
    public R<Page<Volunteer>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String college,
            @RequestParam(required = false) String sex,
            @RequestParam(required = false) String clazz,
            @RequestParam(required = false) String stuId,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        Page<Volunteer> pageInfo = new Page<>(page, size);
        LambdaQueryWrapper<Volunteer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Volunteer::getName, name)
                   .like(StringUtils.isNotEmpty(college), Volunteer::getCollege, college)
                   .eq(StringUtils.isNotEmpty(sex), Volunteer::getSex, sex)
                   .like(StringUtils.isNotEmpty(clazz), Volunteer::getClazz, clazz)
                   .like(StringUtils.isNotEmpty(stuId), Volunteer::getStuId, stuId)
                   .ge(StringUtils.isNotEmpty(startTime), Volunteer::getCreateTime, startTime)
                   .le(StringUtils.isNotEmpty(endTime), Volunteer::getCreateTime, endTime)
                   .orderByDesc(Volunteer::getCreateTime);
        volunteerService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    @GetMapping("/detail/{id}")
    @ApiOperation(value = "获取志愿者详情", notes = "根据ID获取志愿者详细信息")
    @ApiImplicitParam(name = "id", value = "志愿者ID", required = true, dataType = "Integer", paramType = "path")
    public R<Volunteer> detail(@PathVariable Integer id) {
        Volunteer volunteer = volunteerService.getById(id);
        return R.success(volunteer);
    }

    @PostMapping("/admin/add")
    @ApiOperation(value = "添加志愿者", notes = "管理员添加新志愿者")
    @ApiImplicitParam(name = "volunteer", value = "志愿者信息", required = true, dataType = "Volunteer")
    public R<String> add(@RequestBody Volunteer volunteer) {
        volunteer.setCreateTime(LocalDateTime.now());
        volunteer.setUpdateTime(LocalDateTime.now());
        volunteer.setStatus(1);
        volunteerService.save(volunteer);
        return R.success("添加成功");
    }

    @PutMapping("/admin/update")
    @ApiOperation(value = "更新志愿者信息", notes = "管理员更新志愿者信息")
    @ApiImplicitParam(name = "volunteer", value = "志愿者信息", required = true, dataType = "Volunteer")
    public R<String> adminUpdate(@RequestBody Volunteer volunteer) {
        volunteer.setUpdateTime(LocalDateTime.now());
        volunteerService.updateById(volunteer);
        return R.success("更新成功");
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除志愿者", notes = "根据ID删除志愿者")
    @ApiImplicitParam(name = "id", value = "志愿者ID", required = true, dataType = "Integer", paramType = "path")
    public R<String> delete(@PathVariable Integer id) {
        volunteerService.removeById(id);
        return R.success("删除成功");
    }

    @DeleteMapping("/batchDelete")
    @ApiOperation(value = "批量删除志愿者", notes = "根据ID数组批量删除志愿者")
    @ApiImplicitParam(name = "ids", value = "志愿者ID数组", required = true, dataType = "List", paramType = "body")
    public R<String> batchDelete(@RequestBody List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return R.error("请选择要删除的志愿者");
        }
        volunteerService.removeByIds(ids);
        return R.success("批量删除成功");
    }
    
    /**
     * 统计志愿者数量
     *
     * @return 志愿者总数
     */
    @GetMapping("/count")
    @ApiOperation(value = "统计志愿者数量", notes = "获取系统中的志愿者总数")
    public R<Long> count() {
        long count = volunteerService.count();
        return R.success(count);
    }

    @PostMapping("/sendMsg")
    @ApiOperation(value = "发送手机短信验证码", notes = "发送手机短信验证码,参数格式：{\n" +
            "  \"phone\": \"15819291195\"\n" +
            "}")
    @ApiImplicitParam(name = "volunteer.phone", value = "志愿者信息", required = true, dataType = "Volunteer")
    public R<String> sendMsg(@RequestBody Volunteer volunteer, HttpSession session) {
        //获取手机号
        String phone = volunteer.getPhone();

        if (StringUtils.isNotEmpty(phone)) {
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}", code);

            //调用阿里云提供的短信服务API完成发送短信
            smsUtils.sendMessage(phone, code);

            //需要将生成的验证码保存到Session
            session.setAttribute(phone, code);

            return R.success("手机验证码短信发送成功");
        }

        return R.error("短信发送失败");
    }

    @PostMapping("/login")
    @ApiOperation(value = "志愿者登录", notes = "志愿者登录,传入手机号和验证码，参数格式：{\n" +
            "  \"phone\": \"15819291195\",\n" +
            "  \"code\": \"1234\"\n" +
            "}")
    @ApiImplicitParam(name = "map", value = "志愿者信息", required = true, dataType = "Map")
    public R<String> login(@RequestBody Map map, HttpSession session) {
        log.info(map.toString());
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        log.info("phone={},code={}", phone, code);
        //从Session中获取保存的验证码
        Object codeInSession = session.getAttribute(phone);
        log.info("codeInSession={}", codeInSession);
        //进行验证码的比对（页面提交的验证码和Session中保存的验证码比对）
        if (codeInSession != null && codeInSession.equals(code)) {
            //如果能够比对成功，说明登录成功

            LambdaQueryWrapper<Volunteer> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Volunteer::getPhone, phone);

            Volunteer volunteer = volunteerService.getOne(queryWrapper);
            if (volunteer == null) {
                //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
                volunteer = new Volunteer();
                volunteer.setPhone(phone);
                volunteer.setStatus(1);
                volunteerService.save(volunteer);
            }
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", volunteer.getId());

// 修复空指针判断逻辑
            if (volunteer.getName() == null || volunteer.getName().isEmpty()) {  // 先检查null再调用方法
                String ph = volunteer.getPhone();
                volunteer.setName(ph.substring(0,3)+"****"+ph.substring(7));
            }

            claims.put("name", volunteer.getName());
            claims.put("age",volunteer.getAge());
            claims.put("sex",volunteer.getSex());
            claims.put("college",volunteer.getCollege());
            claims.put("clazz",volunteer.getClazz());
            claims.put("stuId",volunteer.getStuId());
            claims.put("createTime",volunteer.getCreateTime());
            claims.put("updateTime",volunteer.getUpdateTime());
            claims.put("status",volunteer.getStatus());
            claims.put("avatar",volunteer.getAvatar());
            claims.put("Age",volunteer.getAge());
            String jwt = JwtUtils.generateJwt(claims);
            return R.success(jwt);
        }
        return R.error("登录失败");
    }
    //更新志愿者信息
    @PutMapping("/update")
    @ApiOperation(value = "更新志愿者信息", notes = "更新志愿者信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "volunteer", value = "志愿者信息", required = true, dataType = "Volunteer"),
            @ApiImplicitParam(name = "token", required = false,paramType = "header",dataType = "String")
    })
    public R<String> update(@RequestBody Volunteer volunteer, HttpServletRequest request)  {
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Integer userId = (Integer) claims.get("userId");
        volunteer.setId(userId);
        volunteerService.updateById(volunteer);
        return R.success("更新成功");
    }
    //获取志愿者信息
    @GetMapping("/get")
    @ApiOperation(value = "获取志愿者信息", notes = "获取志愿者信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", required = false,paramType = "header",dataType = "String")
    })
    public R<Volunteer> get(HttpServletRequest request)  {
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Integer userId = (Integer) claims.get("userId");
        return R.success(volunteerService.getById(userId));


    }



}
